package com.imflea.zero.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Set;

/**
 * @author zhaoyang
 * @version 1.0
 * @project farmplus-service
 * @package com.imflea.zero.utils
 * @filename 创建时间: 2021/12/31
 * @description
 * @copyright Copyright (c) 2021 中国软件与技术服务股份有限公司
 */
@Component
public class TaskTimeOutUtil {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private static RedisTemplate<String, String> stringRedisTemplate;

    @PostConstruct
    public void init() {
        stringRedisTemplate = redisTemplate;
    }

    // 加入任务
    public static boolean enqueue(String queue, String data, int score) {
        return stringRedisTemplate.opsForZSet().add(queue, data, currentSeconds() + score);
    }

    // 从redis中删除任务
    public static Long dequeue(String queue, String data) {
        return stringRedisTemplate.opsForZSet().remove(queue, data);
    }

    public static Set<ZSetOperations.TypedTuple<String>> acquireTimeoutTask(String key, int start, int end) {
        return stringRedisTemplate.opsForZSet().rangeWithScores(key, start, end);
    }

    public static long currentSeconds() {
        return Calendar.getInstance().getTimeInMillis() / 1000;
    }

}
